package com.coder.algorithm.leetcode

import com.coder.algorithm.struct.ListNode

/**
 * [206. 反转链表](https://leetcode-cn.com/problems/reverse-linked-list/)
 *
 * @author yuhus
 * @date: 2022/4/2
 */
object l_0206 {
    /**
     * 递归
     * 分成两部分，头节点和头节点后面节点
     */
    fun reverseList(head: ListNode?): ListNode? {
        if (head?.next == null) {
            return head
        }
        val newHead = reverseList(head.next)
        head.next?.next = head
        head.next = null
        return newHead
    }

    /**
     * 迭代
     */
    fun reverseList_1(head: ListNode?): ListNode? {
        var newHead = head
        var next = head?.next
        while (next != null) {
            head?.next = next.next
            next.next = newHead
            newHead = next
            next = head?.next
        }
        return newHead
    }
}